package com.dingwei.lesyndrome.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.dingwei.lesyndrome.R;
import com.dingwei.lesyndrome.app.MyApplication;
import com.dingwei.lesyndrome.bean.AddressListBean;
import com.dingwei.lesyndrome.mvp.presenter.AddAddressPresenter;
import com.dingwei.lesyndrome.mvp.view.Contract;
import com.lihao.baselibrary.base.BaseActivity;
import com.lihao.baselibrary.weight.TitleBar;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MapActivity extends BaseActivity implements OnGetGeoCoderResultListener,Contract.AddAddressView {
    AddAddressPresenter addAddressPresenter = new AddAddressPresenter(this);

    @Bind(R.id.title_bar)
    TitleBar titleBar;
    @Bind(R.id.bmapView)
    MapView bmapView;
    @Bind(R.id.back_location)
    ImageView backLocation;
    @Bind(R.id.tv_location)
    TextView tvLocation;
    @Bind(R.id.tv_location2)
    TextView tvLocation2;
    @Bind(R.id.btn_check)
    SuperButton btnCheck;
    private BaiduMap mBaiduMap;
    // 定位相关
    private LocationClient mLocClient;
    private LocationClientOption option;
    private GeoCoder mSearch = null; // 搜索模块，也可去掉地图模块独立使用
    public MyLocationListenner myListener = new MyLocationListenner();

    private String current_cor = "";//当前坐标
    private String id;
    private AddressListBean.DataBean dataBean;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_map;
    }

    @Override
    protected void initData() {
        if (TextUtils.isEmpty(id)){
            location();
        }else {
            tvLocation.setText(dataBean.name);
            LatLng ll = new LatLng(Double.parseDouble(dataBean.latitude),
                    Double.parseDouble(dataBean.longitude));
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(15.0f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        }
    }

    public void initView() {

        if (getIntent().hasExtra("dataBean")){
            dataBean = (AddressListBean.DataBean) getIntent().getSerializableExtra("dataBean");
            id = dataBean.id;
        }

        mBaiduMap = bmapView.getMap();
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(15));
        mBaiduMap.setOnMapStatusChangeListener(mapStatusChangeListener);
        // 初始化搜索模块，注册事件监听
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
    }

    public void location() {
        dialog.show();
        tvLocation.setText("获取位置中...");
        // 定位初始化
        if (option == null) {
            option = new LocationClientOption();
            option.setOpenGps(true); // 打开gps
            option.setCoorType("bd09ll"); // 设置坐标类型
            option.setProdName("Alliance"); // 设置产品线名称。强烈建议您使用自定义的产品线名称，方便我们以后为您提供更高效准确的定位服务。
            option.setIsNeedAddress(true);
        }
        if (mLocClient == null) {
            mLocClient = new LocationClient(this);
            mLocClient.registerLocationListener(myListener);
        } else {
            mLocClient.stop();
        }
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    @OnClick({R.id.btn_check, R.id.back_location})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_check:
                String str = tvLocation.getText().toString().trim();
                if (str.equals("获取位置中...") || str.equals("获取位置失败，请拖动地图重新获取")) {
                    showToast("请先获取位置");
                } else {

                    addAddressPresenter.addAddress(id,tvLocation.getText().toString(),current_cor);


                }
                break;
            case R.id.back_location:
                location();
                break;
        }
    }


    BaiduMap.OnMapStatusChangeListener mapStatusChangeListener = new BaiduMap.OnMapStatusChangeListener() {

        @Override
        public void onMapStatusChangeStart(MapStatus mapStatus) {

        }

        @Override
        public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

        }

        /**
         * 地图状态变化中
         *
         * @param status
         *            当前地图状态
         */
        public void onMapStatusChange(MapStatus status) {
        }

        /**
         * 地图状态改变结束
         *
         * @param status
         *            地图状态改变结束后的地图状态
         */
        public void onMapStatusChangeFinish(MapStatus status) {
            tvLocation.setText("获取位置中...");
            tvLocation2.setText("");
            current_cor = status.target.longitude + "," + status.target.latitude;
            LatLng ptCenter = new LatLng(status.target.latitude,
                    status.target.longitude);
            mSearch.reverseGeoCode(new ReverseGeoCodeOption()
                    .location(ptCenter));
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void addSuccess() {
        Intent intent = new Intent();
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            dialog.dismiss();
            // map view 销毁后不在处理新接收的位置
            if (location == null || bmapView == null) {
                tvLocation.setText("获取位置失败，请拖动地图重新获取");
                tvLocation2.setText("");
                return;
            }
            current_cor = location.getLongitude() + "," + location.getLatitude();
            String addrStr = location.getAddrStr();
            if (addrStr.startsWith("中国")) {
                addrStr = addrStr.substring(2, addrStr.length());
            }
            tvLocation.setText(addrStr);
            tvLocation2.setText(location.getLocationDescribe());
            LatLng ll = new LatLng(location.getLatitude(),
                    location.getLongitude());
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(15.0f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        }
    }

    @Override
    protected void onPause() {
        bmapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        bmapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (mLocClient!=null){
            // 退出时销毁定位
            mLocClient.stop();
        }
        if (mBaiduMap!=null){
            // 关闭定位图层
            mBaiduMap.setMyLocationEnabled(false);
        }
        if (bmapView!=null){
            bmapView.onDestroy();
            bmapView = null;
        }
        super.onDestroy();
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
            tvLocation.setText("获取位置失败，请拖动地图重新获取");
            tvLocation2.setText("");
            return;
        }
        String address = reverseGeoCodeResult.getAddress();
        tvLocation.setText(address);
        tvLocation2.setText(reverseGeoCodeResult.getSematicDescription());
    }

}
